package com.hydra.base.utils;

import com.hydra.base.resp.ResultError;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ResponseUtil {

    public static void write(HttpServletResponse response, Object data) throws IOException {
        PrintWriter writer = response.getWriter();
        writer.write(JsonUtil.toJsonString(data));
        writer.flush();
        writer.close();
    }

    public static void writeError(HttpServletRequest request, HttpServletResponse response, HttpStatus httpStatus, String message) throws IOException {
        response.setStatus(httpStatus.value());
        String requestURI = request.getRequestURI();
        ResultError result = ResultError.failure(httpStatus.value(), httpStatus.getReasonPhrase(), message, requestURI);
        PrintWriter writer = response.getWriter();
        writer.write(JsonUtil.toJsonString(result));
        writer.flush();
        writer.close();
    }

}
